/**
  @license
  Copyright 2011 Google Inc. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

/**
 * @author battlehorse@google.com (Riccardo Govoni)
 */

/**
 * Load all the samples for 'Rosling' dataset.
 */
function startRosling(editor, win, doc) {
  loadData(win, doc, function(data) {
    win.dataTable = data;
    editor.addShortCutFromFile('void.html');
    editor.addShortCutFromFile('1.html');
    editor.addShortCutFromFile('2.html');
    editor.addShortCutFromFile('3.html');
    editor.addShortCutFromFile('4.html');
    editor.addShortCutFromFile('5.html');
  });
};

/**
 * Callback invoked when all the libraries required for the demo have been
 * loaded.
 *
 * Load the demo data from Fusion Tables. Since Fusion tables GViz
 * datasource does not allow more than 500 records at a time, we use Fusion
 * Tables Query JSON API and then convert locally into a DataTable.
 *
 * @param {Window} win The iframe window containing the demo contents.
 * @param {Document} doc The document containing the demo contents.
 * @param {Function} callback The callback to invoke upon completion.
 */
function loadData(win, doc, callback) {
  // Check whether we already have the data from localStorage.
  if (win['localStorage'] !== null) {
    var data = win.localStorage['datatable'];
    if (data) {
      if (typeof(console) != 'undefined') {
        console.log('Data loaded from cache');
      }
      win.jQuery(doc.getElementById('content')).fadeIn();
      callback(new win.google.visualization.DataTable(data));
      return;
    }
  }

  // Define a set of basic transformation functions, to adapt the output
  // of the Fusion Tables query to the DataTable format we are going to use.
  var noOp = function(value) { return value; };
  var toInteger = function(value) {
    value = parseInt(value, 10);
    if (isNaN(value)) {
      return null;
    } else {
      return value;
    }
  };
  var toFloat = function(value) {
    value = parseFloat(value);
    if (isNaN(value)) {
      return null;
    } else {
      return value;
    }
  };

  // Define the set of columns that we will extract from Fusion Tables and use
  // in the demo API.
  var colsSpec = {
    'Year': {
      label: 'Year',
      transform: toInteger,
      type: 'number'},
    'Country Name': {
      label: 'Country Name',
      transform: noOp,
      type: 'string'},
    'NY.GDP.PCAP.CD': {
      label: 'GDP per capita (current US$)',
      transform: toFloat,
      type: 'number'},
    'SP.DYN.LE00.IN': {
      label:'Life expectancy at birth, total (years)',
      transform: toFloat,
      type: 'number'}
  };

  // Fetch the Data from Fusion Table via JSONP call
  var queryText = 'select col0, col1, col4, col6 from 680149';
  win.jQuery.ajax({
    url: 'https://www.google.com/fusiontables/api/query?sql=' +
      encodeURIComponent(queryText),
    dataType: 'json',
    jsonp: 'jsonCallback',
    success: function(json) {
      // Convert the JSON output into a suitable DataTable, applying a minimum
      // of formatting and prettifying.
      var rows = json.table.rows;
      var cols = json.table.cols;
      for (var i = 0; i < rows.length; i++) {
        for (var j = 0; j < cols.length; j++) {
          rows[i][j] = colsSpec[cols[j]]['transform'](rows[i][j]);
        }
      }
      var data = new win.google.visualization.DataTable();
      for (var i = 0; i < cols.length; i++) {
        data.addColumn(colsSpec[cols[i]]['type'], cols[i]);

        // Fusion Tables seems to truncate labels. Restore them with local
        // names.
        data.setColumnLabel(i, colsSpec[cols[i]]['label']);
      }
      data.addRows(rows);

      // Apply a minimum of formatting on the data.
      var formatter = new win.google.visualization.NumberFormat({
        'prefix': '$',
        'fractionDigits': 0});
      formatter.format(data, 2);

      formatter = new win.google.visualization.NumberFormat({'fractionDigits': 1});
      formatter.format(data, 3);

      if (win['localStorage'] !== null) {
        // Save to localStorage, if available, for faster reloads during
        // the demo.
        localStorage['datatable'] = data.toJSON();
      }
      if (typeof('console') != 'undefined') {
        console.log('Data loaded from remote source');
      }
      win.jQuery(doc.getElementById('contents')).fadeIn();
      callback(data);
    },
    error: function(jqXhr, txtStatus) {
      alert('Error while fetching data:' + txtStatus);
    }
  });
}

